package com.eliza.spring.boot.library.utils.jwt

import com.auth0.jwt.exceptions.AlgorithmMismatchException
import com.auth0.jwt.exceptions.SignatureVerificationException
import com.auth0.jwt.exceptions.TokenExpiredException
import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.web.servlet.HandlerInterceptor
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

class JWTInterceptor : HandlerInterceptor {
    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
        val hashMap = HashMap<String, Any>()

        var token = request.getHeader("token") ?: ""
        try {
            JwtTools.Verify(JwtTools.JWT_TOKEN, token)
            return true
            /*
            * 不报错即为成功，
            * 若报错则返回报错信息
            * */
        } catch (e: SignatureVerificationException) {
            e.printStackTrace();
            println("无效签名");
            hashMap["msg"] = "无效签名"
        } catch (e: TokenExpiredException) {
            e.printStackTrace();
            println("token过期");

            hashMap["msg"] = "token过期"
        } catch (e: AlgorithmMismatchException) {
            e.printStackTrace();
            println("token算法不一致");

            hashMap["msg"] = "token算法不一致"
        } catch (e: Exception) {
            e.printStackTrace();
            println("token无效");

            hashMap["msg"] = "token无效"
        }
        hashMap.put("state", false)
        response.also {
            it.contentType = "application/json;charset=UTF-8"
            it.writer.println(ObjectMapper().writeValueAsString(hashMap))
        }
        return false
    }
}